<template>
	<view class="root">
		<u-popup :show="popupShow" mode="right" bgColor="#161823" safeAreaInsetTop></u-popup>
		<view class="">
			<view class="">
				<view class="groupTitle"><text>照护信息</text></view>
				<view class="actionTitle">
					<text>被护理人：{{order.zhsq ? order.zhsq.bisZhsqSnryXm : ''}}</text>
				</view>
				<view class="actionTitleRq">
					<text>计划护理日期：{{order ? order.bisOrderHlrq : ''}}</text><br/>
				</view>
				<view class="actionTitleSJ">
					<text>计划护理时间：{{order ? order.bisOrderStartTime : ''}} - {{order ? order.bisOrderEndTime : ''}}</text>
				</view>
				<view class="actionTitleSJ">
					<text>实际护理时间：{{order ? order.bisOrderHlstart : ''}}</text>
				</view>
			</view>
			<view class="" v-if="order.bisOrderZt === '0'">
				<view class="actionButtonGroup">
				<!-- 	<button class="actionButton" v-if="faceFlag === 0" @click="toFaceRecognition">人脸识别</button> -->
				<!-- 	<button class="actionButton" v-if="faceFlag === 1" @click="startHl" :disabled="disabled">开始护理</button> -->
				<button class="actionButton" @click="startHl" :disabled="disabled">开始护理</button>
				</view>
				<view class="actionMessage">
					<text class="textMessage" style="color: red;">{{message}}</text>
				</view>
			</view>
			<view v-if="order.bisOrderZt !== '0'">
				<view class="groupTitle"><text>订单明细</text></view>
				<uni-collapse ref="collapse" accordion>
					<uni-collapse-item  v-for="(item,index) in order.orderMxList" :key="item.bisOrderMxId">
						<template v-slot:title>
							<view class="detailedTitle">
								<view class="detailedTitleText">{{item.bisOrderFwmc}}</view>
								<view class="detailedTitleCheck"><checkbox disabled :checked="item.beforePhoto && item.hlVideo && item.afterPhoto"/></view>
							</view>
						</template>
						<view class="actionGroup">
							
							<view class="detailedPhotoView">
								<view class="actionItem" v-if="item.beforePhoto">
									<uni-icons class="deleteImg" type="clear" size="30" @click="deleteImg('beforePhoto',item)" v-if="editAble"></uni-icons>
									<image style="width: 100%;height: 100%;" :src="item.beforePhoto.path" @click="previewImage('beforePhoto',item)"></image>
								</view>
								<view class="actionItem" v-if="!item.beforePhoto && editAble">
									<uni-icons type="camera" size="100" @click="selectImg('beforePhoto',item)"></uni-icons>
								</view>
								<view class="">护理前照片</view>
							</view>
							<view class="detailedPhotoView">
								
								<view class="actionItem" v-if="item.hlVideo">
									<uni-icons class="deleteImg" type="clear" size="30" @click="deleteImg('hlVideo',item)" v-if="editAble"></uni-icons>
									<video class="video" :src="item.hlVideo.path"
											@error="videoErrorCallback" controls></video>
								</view>
								<view class="actionItem videoItem" v-if="!item.hlVideo && editAble">
									<uni-icons type="videocam" size="100" @click="selectImg('hlVideo',item)"></uni-icons>
								</view>
								<view class="">护理视频</view>
							</view>
							<view class="detailedPhotoView">
								<view class="actionItem" v-if="item.afterPhoto">
									<uni-icons class="deleteImg" type="clear" size="30" @click="deleteImg('afterPhoto',item)" v-if="editAble"></uni-icons>
									<image style="width: 100%;height: 100%;" :src="item.afterPhoto.path" @click="previewImage('afterPhoto',item)"></image>
								</view>
								<view class="actionItem" v-if="!item.afterPhoto && editAble">
									<uni-icons type="camera" size="100" @click="selectImg('afterPhoto',item)"></uni-icons>
								</view>
								<view class="">护理后照片</view>
							</view>
						</view>
					</uni-collapse-item>
				</uni-collapse>
				
				<view class="snryHeZhao"><text>护理员与失能人员合照</text></view>
				<view class="snryHeZhaoView">
					<view class="actionItem" v-if="order.orderMxList[0].groupPhoto">
						<uni-icons class="deleteImg" type="clear" size="30" @click="deleteImg('groupPhoto',order.orderMxList[0])" v-if="editAble"></uni-icons>
						<image style="width: 100%;height: 100%;" :src="order.orderMxList[0].groupPhoto.path" @click="previewImage('groupPhoto',order.orderMxList[0])"></image>
					</view>
					<view class="actionItem" v-if="!order.orderMxList[0].groupPhoto && editAble">
						<uni-icons type="camera" size="100" @click="selectImg('groupPhoto',order.orderMxList[0])"></uni-icons>
					</view>
				</view>
				
			</view>
			
			<view class="actionButtonGroup" v-if="editAble && order.bisOrderZt !== '0'">
				<text style="color: red;">{{prompt}}</text>
				<button class="actionButton" @click="formSubmit2" :disabled="isReadyToSubmit">完成</button>
			</view>
		</view>
	</view>
</template>

<script lang="ts">
	
	import { route,routeMixin } from "@/route/Route"
	import { orderService } from '@/service/OrderService'
	import { orderMxService } from '@/service/OrderMxService'
	import { localStoreService } from '@/service/LocalStoreService'
	
	import { loading } from '@/loading/Loading'
	import moment from "moment"
	
	export default {
		mixins:[routeMixin],
		data() {
			return {
				prompt: '',
				isCamera:[''],
				message: '',
				disabled: false,
				time: 0,
				captchaText: '获取验证码',
				popupShow:false,
				order:{},
				arr:[],
				hlkssj: '',
				isReadyToSubmit: false,  
				orderMxPageReq:{
					page: 0,
					size: 100,
					sort: "BIS_ORDER_FWBM,ASC"
				},
				editAble: false,
				faceFlag: 0,
				groupPhoto: '',
				buttonflag: false
			}
		},
		methods: {
			getTimeThirtyMinutesBefore(specifiedTime) {  
			  const parsedTime = moment(specifiedTime, 'YYYY-MM-DD HH:mm:ss');   
			  // 获取三十分钟之前的时间  
			  const thirtyMinutesBefore = parsedTime.subtract(30, 'minutes');  
			  return thirtyMinutesBefore;  
			},
			getTimeThirtyMinutesAfter(specifiedTime) {  
			  const parsedTime = moment(specifiedTime, 'YYYY-MM-DD HH:mm:ss');  
			  // 获取三十分钟之后的时间  
			  const thirtyMinutesAfter = parsedTime.add(30, 'minutes');  
			  return thirtyMinutesAfter;  
			},
			getTimeThirtyMinutes180(specifiedTime) {
			  const parsedTime = moment(specifiedTime, 'YYYY-MM-DD HH:mm:ss');  
			  // 获取180分钟之后的时间  
			  const thirtyMinutes180 = parsedTime.add(180, 'minutes');  
			  return thirtyMinutes180;  
			},
			getTimeThirtyMinutes120(specifiedTime) {
			  const parsedTime = moment(specifiedTime, 'YYYY-MM-DD HH:mm:ss');  
			  // 获取180分钟之后的时间  
			  const thirtyMinutes120 = parsedTime.add(120, 'minutes');  
			  return thirtyMinutes120;  
			},
			routeParameterEvent(data) {
				// 设置是否默认打开相机或相册
				this.isCamera = data.bisOrderXjzt === '1' ? ['camera'] : ['album','camera'];
				this.isCamera = data.bisOrderXjzt === '2' ? ['album','camera'] : ['camera'];
				// 获取当前时间  
				const now = moment();
				console.log('from data1 : {}===============',data)
				const dateTim = data.bisOrderHlrq + data.bisOrderStartTime
				const parsedTime = moment(dateTim,"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
				
				const thirtyMinutesBefore = this.getTimeThirtyMinutesBefore(parsedTime).format('YYYY-MM-DD HH:mm:ss');  	
				const thirtyMinutesAfter = this.getTimeThirtyMinutesAfter(parsedTime).format('YYYY-MM-DD HH:mm:ss');
			
				// 开始护理时间 小于 设定的护理时间
				const isBefore = now.isBefore(thirtyMinutesBefore);
				// 开始护理时间 大于 设定的护理时间
				const isAfter = now.isAfter(thirtyMinutesAfter);
				if(isBefore){
					this.disabled = true;
					this.message = "护理时间未到！"+"\n"+"开始护理时间为："+"\n"+thirtyMinutesBefore+"~~"+thirtyMinutesAfter+"\n";
				} else if (isAfter){
					this.disabled = true;
					this.message = "护理时间已过！"+"\n"+"开始护理时间为："+"\n"+thirtyMinutesBefore+"~~"+thirtyMinutesAfter+"\n";
				}
				this.routeParameter = data
				this.editAble = data.editAble
				// 是否缴费记录
				orderMxService.getPersonNoFee({sfzh:data.zhsq.bisZhsqSnrySfz},(res1)=>{
					console.log("getPersonNoFee {}", res1)
					if(res1.size === 0){
						this.disabled = true;
						this.message += "未查询到缴费记录！"+"\n";
					}
				})
				// 是否账户封存
				orderMxService.getPersonNoFc({sfzh:data.zhsq.bisZhsqSnrySfz},(res2)=>{
					if(res2.size > 0){
						this.disabled = true;
						this.message += "账户处于封存状态！"+"\n";
					}
				})
				// 是否校验过人脸识别
				orderService.queryVerifyPersonCnt({bisOrderId: data.bisOrderId},(res)=>{
					console.log("queryVerifyPersonCnt {}", res)
					if(res == 0) {
						this.faceFlag = 0;
					} else {
						this.faceFlag = 1
					}
				})
				orderMxService.orderMxList({bisOrderId:data.bisOrderId},(res)=>{
					// 限制：开始护理-结束护理180分钟
					const parsedTime = moment(data.bisOrderHlstart,"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
					const endTime = this.getTimeThirtyMinutes180(parsedTime).format('YYYY-MM-DD HH:mm:ss');
					// 当前时间必须小于 护理结束时间
					const now = moment();
					const isBefore = now.isBefore(endTime);
					if(!isBefore){
						this.isReadyToSubmit = true
						this.prompt = "护理结束时间已过(限制180分钟内完成)";
					}
					data.orderMxList = res
					var cnt = 0
					for(let item of res){
						for(let s of item.localStorageList){
							switch(s.fjlb){
								case 'beforePhoto':
									item.beforePhoto = s
									break;
								case 'hlVideo':
									item.hlVideo = s
									break;
								case 'afterPhoto':
									item.afterPhoto = s
									break;
								case 'groupPhoto':
									if(cnt === 0) {
										item.groupPhoto = s
										console.log("orderMxList {}", s)
										break;
									}
									cnt++;
								default:
									
							}
						}
					}
					this.order = data
				})
				
			},
			formSubmit2() {
				
				let _this = this
				orderService.execute({
						bisOrderId:_this.order.bisOrderId,
						bisOrderZt:'1',
						bisOrderZhid: _this.order.bisOrderZhid,
						bisOrderServiceType:  _this.order.bisOrderServiceType,
					},(res)=>{
						loading.hidden()
						console.log(res)
				})
			},
			formSubmit(){
				// 获取当前时间
				const now2 = moment();	
				// 限制：开始护理-结束护理180分钟
				const parsedTime = moment(this.order.bisOrderHlstart,"YYYY-MM-DD HH:mm:ss").format("YYYY-MM-DD HH:mm:ss");
				const endTime = this.getTimeThirtyMinutes180(parsedTime).format('YYYY-MM-DD HH:mm:ss');
				const isBefore = now2.isBefore(endTime);
				if(!isBefore){
					this.isReadyToSubmit = true
					this.prompt = "护理结束时间已过(限制180分钟内完成)";
				}
				// 限制：开始护理-结束护理 小于120分钟不能提交
				const HLEndTime = this.getTimeThirtyMinutes120(parsedTime).format('YYYY-MM-DD HH:mm:ss');
				const isBefore2 = now2.isBefore(HLEndTime);
				console.log("=========",this.order)
				if(isBefore2){
					this.isReadyToSubmit = true
					this.prompt = "护理结束时间未到(护理时长不能小于两小时)";
					uni.showToast({
						icon:'error',
						title: "护理结束时间未到(护理时长不能小于两小时)",
						duration: 2000
					});
					return
				}
				let v = true
				let vMsg = ""
				for(let item of this.order.orderMxList){
					if(!item.beforePhoto || !item.hlVideo || !item.afterPhoto){
						v = false
						vMsg = item.bisOrderFwmc
						break;
					}
				}
				
				if(!v){
					uni.showToast({
						icon:'error',
						title: vMsg+"尚未护理",
						duration: 2000
					});
					return
				}
				if(!this.order.orderMxList[0].groupPhoto){
					uni.showToast({
						icon:'error',
						title: "未上传与失能人员合照",
						duration: 2000
					});
					return
				}
				
				let _this = this
				uni.showModal({
					title: '提示',
					content: '是否确认提交',
					success: function (res) {
						if (res.confirm) {
						loading.show()
							orderService.execute({
									bisOrderId:_this.order.bisOrderId,
									bisOrderZt:'1',
									bisOrderZhid: _this.order.bisOrderZhid,
									bisOrderServiceType:  _this.order.bisOrderServiceType,
								},(res)=>{
									loading.hidden()
									console.log(res)
									route.goBack()
							})
						} else if (res.cancel) {
						}
					}
				});
				
			},
			uploadFile(type,item,file){
				loading.show()
				const _this = this
				console.log(file)
				uni.uploadFile({
					url: process.env.VUE_APP_PUBLIC_FILE_PATH,
					filePath: file.path,
					name: 'file',
					success: (uploadFileRes) => {
						console.log(uploadFileRes)
						let data = JSON.parse(uploadFileRes.data)
						localStoreService.addLocalStorage({
							realName: data.filename,
							name: data.filename,
							path: data.url,
							size: file.size,
							ywid: item.bisOrderMxId,	
							fjlb: type
						},(res)=>{
							item[type] = res
							console.log(res)
						})
					},
					complete() {
						loading.hidden()
					}
				});
				
			},
			selectImg(type,item) {
				const _this = this
				if(type === "hlVideo"){
					uni.chooseVideo({
						sourceType: this.isCamera,
						success: function (res) {
							console.log(res)
							console.log("===================",res.duration)
							if(res.duration >= 10){
								res.path = res.tempFilePath
								_this.uploadFile(type,item,res)
							} else {
								uni.showToast({
									icon:'error',
									title: "视频时长不能小于10秒",
									duration: 2000
								});
								return
							}
						}
					});
				}else{
					uni.chooseImage({
						sourceType: this.isCamera,
						success: function(chooseImageRes) {
							let file = chooseImageRes.tempFiles[0]
							_this.uploadFile(type,item,file)
						}
					});
				}
					
				
			},
			previewImage(type,item){
				// 预览图片
				uni.previewImage({
					urls: [item[type].path],
				});
			},
			deleteImg(type,item){
				localStoreService.delLocalStorage([item[type].id],(res)=>{
					
					item[type] = undefined
				})
			},
			startHl(){	
				
				let _this = this
				
				uni.showModal({
					title: '提示',
					content: '是否开始护理',
					success: function (res) {
						console.log("==============",res)
						if (res.confirm) {
							uni.authorize({
							    scope: 'scope.userLocation',
							    success() {
									loading.show()
							        console.log("授权成功")
							        uni.getLocation({
							        	type: 'gcj02',
							        	isHighAccuracy: true,
							        	success: function (resl) {
							        		console.log('当前位置：',res);
											orderService.getZhJWDtest({
													bisOrderZhid: _this.order.bisOrderZhid,
													ordjd: resl.longitude,
													ordwd: resl.latitude,
												},(res2)=>{
												console.log("距离",res2.meter,"米")
												if(res2.meter > 200){
													_this.disabled = true;
													_this.message = res2.msg;
													loading.hidden()
												} else {
													orderService.startHl({
															bisOrderId:_this.order.bisOrderId,
															bisOrderZhid: _this.order.bisOrderZhid,
															bisOrderServiceType:  _this.order.bisOrderServiceType,
															bisOrderJd: resl.longitude,
															bisOrderWd: resl.latitude,
														},(res)=>{
															_this.order.bisOrderZt = '3'
															loading.hidden()
													})	
												}	
											})	
							        	},
										fail(e) {
											console.log(e)
											loading.hidden()
										}
							        });
							    },
								fail() {
									
									uni.showToast({
										icon:'error',
										title: "请对地理位置信息进行授权",
										duration: 2000
									});
								}
							})
							
						} else if (res.cancel) {
						}
					}
				});
			},
			openMenu() {
			  this.popupShow = true;
			},
			closeMenu() {
			  this.popupShow = false;
			},
			toFaceRecognition(){
				route.navigateTo({name:'faceRecognition',parameter:{
					orderId: this.routeParameter.bisOrderId,
					userId: this.routeParameter.bisOrderHlyId,
				}})
			},
			fromRouteParameterEvent: function(id, data) {
				console.log(data)
				if(data.flag === '1' && data.isMatch === 'true') {
					this.faceFlag = 1;
				} else {
					uni.showToast({
						icon:'error',
						title: "头像校验失败，请重试",
						duration: 3000
					});
				}
			},
			
		}
	}
</script>

<style lang="scss">
	.root {
		display: flex;
		flex-direction: column;
	}
	// .videoItem{
		
	// 		width: 200rpx;
	// 		height: 200rpx;
	// }
	.video{
		width: 200rpx;
		height: 200rpx;
	}
	.groupTitle {
		height: 80rpx;
		background-color: $uni-bg-color-grey;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		padding-left: 40rpx;
		font-size: 36rpx;
		font-weight: 700;
	}
	
	.snryHeZhao {
		height: 80rpx;
		background-color: $uni-bg-color-grey;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		padding-left: 40rpx;
		font-size: 36rpx;
		font-weight: 700;
	}

	.actionTitle {
		height: 80rpx;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		padding-left: 40rpx;
		font-size: 28rpx;
	}
	.actionTitleRq {
		height: 80rpx;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		padding-left: 40rpx;
		font-size: 28rpx;
	}
	
	.actionTitleSJ {
		height: 80rpx;
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
		padding-left: 40rpx;
		font-size: 28rpx;
	}

	.actionGroup {
		display: flex;
		flex-direction: row;
		flex-wrap: wrap;
		justify-content: flex-start;
		align-items: center;
		padding-left: 40rpx;
	}

	.actionItem {
		width: 200rpx;
		height: 200rpx;
		margin: 10rpx;
		border: 4rpx $uni-bg-color-grey solid;
		position: relative;
	}
	.deleteImg{
		color: red !important;
		font-size: 60rpx !important;	
		position: absolute;
		z-index: 9;
		right: -30rpx;
		top: -30rpx;
	}
	.actionButtonGroup{
		display: flex;
		flex-wrap: wrap;
		justify-content: center;
		width: -webkit-fill-available;
		padding-top: 30rpx
	}
	.actionButton{
		width: 280rpx;
		// margin: 20rpx;
		background-color: $uni-primary;
		color: $uni-white;
	}
	.detailedTitle{
		display: flex;
		flex-direction: row;
		padding: 14px 18px;
		justify-content: flex-start;
		align-items: center;
	}
	
	.detailedTitleText{
		
	}
	.detailedTitleCheck{
		padding-left: 12px;
	}
	.detailedPhotoView{
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}
	.popupShow {
		overflow: hidden;
		position: fixed;
	}
	.actionMessage {
		text-align: center;
	}
	
	.textMessage{
		display: flex;
		flex-direction: row;
		justify-content: center;
		align-items: center;
		padding-left: 0rpx;
		font-size: 30rpx;
	}
</style>
